﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Shopping.BLL;
using Shopping.Model;
using Shopping.Common;

public partial class Home_AS_OrderInfoCommon : BaseUserPage
{
    private readonly PayModesManage _payModesManage = new PayModesManage();
    private readonly ShoppingCartsManage _shoppingCartsManage = new ShoppingCartsManage();
    private readonly UserCouponsManage _couponsManage = new UserCouponsManage();
    private readonly DeliveryManage _deliveryManage = new DeliveryManage();
    private readonly OrdersManage bllOrder = new OrdersManage();
    private readonly UserAddressManage bllAddress = new UserAddressManage();

    protected List<PayModes> _payModesList = new List<PayModes>();
    protected List<ShoppingCartInfo> _shoppingCartsList = new List<ShoppingCartInfo>();
    protected List<UserCouponInfo> _couponList = new List<UserCouponInfo>();
    protected List<Deliveries> _deliveries = new List<Deliveries>();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            var action = Request.QueryString["Action"] + "";
            switch (action.ToLower())
            {
                case "userreciveinfo":
                    UserReciveInfo();
                    break;
                case "payinfo":
                    PayInfo();
                    break;
                case "orderinfo":
                    OrderInfo();
                    break;
                case "findcoupon":
                    Coupon();
                    break;
                case "adduseraddress":
                    AddUserAddress();
                    break;
                case "orderfee":
                    OrderFee();
                    break;
                case "submitorder":
                    SubmitOrder();
                    break;
                case "computesendfee": //计算运费； by 赵国伟 2012-08-20
                    ComputeSendFee();
                    break;
                case "saveorder":  //保存订单信息； by 赵国伟 2012-08-20
                    SaveOrder();
                    break;
                case "cancelorder": //取消指定用户的订单；by 赵国伟 2012-08-20
                    CancelOrder();
                    break;
            }
            Response.End();
        }
    }

    #region "取消一条指定用户的订单； by 赵国伟 2012-08-20"
    /// <summary>
    /// 取消一条指定用户的订单；
    /// </summary>
    private void CancelOrder()
    {
        int orderId = Utility.G<int>("OrderID");
        Response.Write(bllOrder.ModifyStatus(this.UserID, orderId, OrderStatus.已取消).ToJsonString());
    }
    #endregion


    #region "保存订单信息 by  赵国伟 2012-08-20"
    /// <summary>
    /// 保存订单信息；
    /// </summary>
    private void SaveOrder()
    {
        int UserAddressID = Utility.P<int>("UserAddressID");

        //获取客户端提交上来的数据；结构为json结构；
        string jsonData = Request["jsonData"] + "";  //获取传递过来的Json对象数据；
        OrderInfo o = null;
        ReturnValue ret = new ReturnValue();
        try
        {
            ///将提交上来的Json格式的数据装化为相应的实体类；
            o = JSONHelper.JsonStringToObject<OrderInfo>(jsonData);
        }
        catch (Exception e)
        {
            ret.Message = "订单保存失败！" ;
            Response.Write(ret.ToJsonString());
            return;
        }
        o.Order.OrderDate = DateTime.Now;
        o.Order.OrderStatus = OrderStatus.等待付款.ToString();
        o.Order.UserID = this.UserID;
        ret = bllOrder.SaveOrder(o);
        if (ret.IsSucc)
        {

            //清空购物车；
            _shoppingCartsManage.Clear(_shoppingCartsManage.GetShoppingCartCookieName(this.UserID));

            //更新本次的收获地址为默认；没有则新增；
            UserAddress a = new UserAddress();
            a.UserID = this.UserID;
            a.IsDefault = true;
            a.UserAddressID = UserAddressID;
            a.AreaID = o.Order.AreaID;
            a.CreateDate = DateTime.Now;
            a.LastModifyDate = DateTime.Now;
            a.ReceiverAddress = o.Order.ReceiverAddress;
            a.ReceiverMobile = o.Order.ReceiverMobile;
            a.ReceiverName = o.Order.ReceiverName;
            a.ReceiverPhone = o.Order.ReceiverPhone;
            a.ReceiverZipCode = o.Order.ReceiverZipCode;
            bllAddress.Save(a);
            ret.Data = o.Order.OrderID;
        }
        
        Response.Write(ret.ToJsonString());

    }
    #endregion


    #region "计算快递费用；by 赵国伟 2012-08-20"
    /// <summary>
    /// 计算快递费用；
    /// </summary>
    private void ComputeSendFee()
    {
        int deliveryID = Utility.G<int>("DeliveryID");
        int areaId = Utility.G<int>("AreaID");
        int totalWeight = Utility.G<int>("totalWeight");
        ReturnValue ret = new ReturnValue(ResultType.Success);
        ret.Message = Utility.FormatMoneyStr(_deliveryManage.ComputeSendFee(deliveryID, areaId, totalWeight));
        Response.Write(ret.ToJsonString());
    }
    #endregion




    private decimal CalcSendFee(List<ShoppingCartInfo> shoppingCartsList, int areaId, string sendmode)
    {
        var sendfee = 0.0m;
        var weight = 0.0m;
        GoodsManage gmanage = new GoodsManage();
        _deliveries = _deliveryManage.Query(true);

        var delivery = sendmode != "undefined" ? _deliveries.Single(d => d.DeliveryName == sendmode) : _deliveries[0];
        QueryDeliveryFeeAsPage asPage = new QueryDeliveryFeeAsPage(true);
        asPage.AreaID = areaId;
        asPage.DeliveryID = delivery.DeliveryID;
        asPage.PageSize = 1;


        var feelist = _deliveryManage.QueryDeliveryFeeAsPage(asPage);

        for (var i = 0; i < shoppingCartsList.Count; i++)
        {
            var goods = gmanage.GetGoods(shoppingCartsList[i].CartInfo.GoodsID);
            weight += goods.BaseInfo.Weight * shoppingCartsList[i].CartInfo.Quantity;
        }
        var firstweight = delivery.FirstWeight;
        var firstfee = delivery.FirstWeightFee;
        var addweight = delivery.PerWeight;
        var addfee = delivery.PerWeightFee;
        if (feelist != null && feelist.Count > 0)
        {
            firstweight = feelist[0].Fee.FirstWeight;
            firstfee = feelist[0].Fee.FirstWeightFee;
            addweight = feelist[0].Fee.PerWeight;
            addfee = feelist[0].Fee.PerWeightFee;
        }
        if (weight <= firstweight)
        {
            sendfee = firstfee;
        }
        else
        {
            sendfee = firstfee + ((weight - firstweight) % addweight == 0 ? Convert.ToInt32((weight - firstweight) / addweight) * addfee : ((Convert.ToInt32((weight - firstweight) / addweight) + 1) * addfee));
        }
        return sendfee;
    }

    private void SubmitOrder()
    {
        /*
        var fapiao = Utility.G<string>("fapiao");
        var coupon = Utility.G<int>("coupon");
        var paymode = Utility.G<string>("paymode");
        var addressid = Utility.G<int>("addressId");
        var sendmode = Utility.G<string>("sendmode");
        var remark = Utility.G<string>("remark");

        var totalprice = Utility.G<decimal>("totalprice");
        var sendfee = Utility.G<decimal>("sendfee");
        OrdersManage omanage = new OrdersManage();
        UserAddressManage umanage = new UserAddressManage();

        var addresslist = umanage.QuerList(UserID);
        UserAddress selectedAddress = null;
        if (addresslist != null && addresslist.Count > 0)
        {
            selectedAddress = addresslist.Single(a => a.AddressInfo.UserAddressID == addressid);
        }
        if (selectedAddress == null)
        {
            Response.Write(JSONHelper.ObjectToJson(new ReturnValue(ResultType.Fail, "请选择送货地址")));
            return;
        }
        var couponinfo = _couponsManage.GetCouponInfoById(coupon, UserID);
        if (couponinfo == null && coupon != 0)
        {
            Response.Write(JSONHelper.ObjectToJson(new ReturnValue(ResultType.Fail, "没有该优惠券信息")));
            return;
        }
        //计算运费
        _shoppingCartsList = _shoppingCartsManage.QueryList(_shoppingCartsManage.GetShoppingCartCookieName(UserID));
        if (_shoppingCartsList != null && _shoppingCartsList.Count > 0)
        {
            sendfee = CalcSendFee(_shoppingCartsList, selectedAddress.AreaID, sendmode);
            var goodprice = _shoppingCartsList.Sum(s => s.CartInfo.Price * s.CartInfo.Quantity);
            totalprice = goodprice + sendfee - (coupon != 0 ? couponinfo.Coupon.CouponMoney : 0);
        }
        else
        {
            Response.Write(JSONHelper.ObjectToJson(new ReturnValue(ResultType.Fail, "购物车中没有任何商品")));
            return;
        }

        //验证支付方式
        if (string.IsNullOrEmpty(paymode))
        {
            Response.Write(JSONHelper.ObjectToJson(new ReturnValue(ResultType.Fail, "请选择支付方式")));
            return;
        }
        //验证送货方式
        if (string.IsNullOrEmpty(sendmode))
        {
            Response.Write(JSONHelper.ObjectToJson(new ReturnValue(ResultType.Fail, "请选择送货方式")));
            return;
        }

        //生成订单信息
        OrderInfo o = new Shopping.Model.OrderInfo();
        o.UserName = UserName;
        o.Order = new Orders();
        o.Order.FaPiao = fapiao;
        o.Order.OrderDate = DateTime.Now;
        o.Order.OrderStatus = "";
        o.Order.PayMode = paymode;
        o.Order.AreaID = selectedAddress.AreaID;
        o.Order.ReceiverAddress = selectedAddress.ReceiverAddress;
        o.Order.ReceiverMobile = selectedAddress.ReceiverMobile;
        o.Order.ReceiverName = selectedAddress.ReceiverName;
        o.Order.ReceiverPhone = selectedAddress.ReceiverPhone;
        o.Order.ReceiverZipCode = selectedAddress.ReceiverZipCode;
        o.Order.SendMode = sendmode;
        o.Order.TotalAmount = totalprice;
        o.Order.UserID = UserID;
        o.Order.SendFee = sendfee;
        o.Order.Remark = remark;
        o.Order.OrderStatus = OrderStatus.等待付款.ToString();
        if (couponinfo != null && couponinfo.Coupon.CouponID != 0)
        {
            o.Order.CouponSN = couponinfo.UserCoupon.CouponID;
            o.Order.CouponMoney = couponinfo.Coupon.CouponMoney;
        }

        o.Lines = new List<OrderLineInfo>();
        _shoppingCartsList = _shoppingCartsManage.QueryList(_shoppingCartsManage.GetShoppingCartCookieName(UserID));
        if (_shoppingCartsList != null && _shoppingCartsList.Count > 0)
        {
            for (var i = 0; i < _shoppingCartsList.Count; i++)
            {
                var ol = new OrderLineInfo();
                ol.GoodsName = _shoppingCartsList[i].GoodsName;
                ol.LineInfo = new OrderLines();
                ol.LineInfo.Discount = 0;
                ol.LineInfo.GoodsID = _shoppingCartsList[i].CartInfo.GoodsID;
                ol.LineInfo.PresentScores = _shoppingCartsList[i].CartInfo.PresentScores;
                ol.LineInfo.Price = _shoppingCartsList[i].CartInfo.Price;
                ol.LineInfo.Quantity = _shoppingCartsList[i].CartInfo.Quantity;
                ol.LineInfo.PackUnitID = _shoppingCartsList[i].CartInfo.PackUnitID;
                o.Lines.Add(ol);
            }
        }
        ReturnValue ret = omanage.SaveOrder(o);

        if (ret.IsSucc)
        {
            _shoppingCartsManage.Clear(_shoppingCartsManage.GetShoppingCartCookieName(UserID));
            if (couponinfo != null && couponinfo.Coupon.CouponID != 0)
            {
                // couponinfo.UserCoupon.
            }
        }
        //if (!ret.IsSucc)
        //{
        
            Response.Write(JSONHelper.ObjectToJson(ret));
        //}
        //else
        //{
        //    ret.Message="";
        //    Response.Write(JSONHelper.ObjectToJson(
        //}
         * 
         */
    }

    private void OrderFee()
    {
        //_shoppingCartsList = _shoppingCartsManage.QueryList(_shoppingCartsManage.GetShoppingCartCookieName(this.UserID));
        //if (_shoppingCartsList == null || _shoppingCartsList.Count <= 0)
        //{
        //    Response.Write("{goodsprice:0,sendfee:0}");
        //    return;
        //}
        //var goodprice = _shoppingCartsList.Sum(shoppingcart => shoppingcart.CartInfo.Price * shoppingcart.CartInfo.Quantity);
        //var addressid = Utility.G<int>("addressid");
        //var sendmode = Utility.G<string>("sendmode");

        //UserAddressManage umanage = new UserAddressManage();
        //var addresslist = umanage.QuerList(UserID);
        //UserAddress selectedAddress = null;
        //if (addresslist != null && addresslist.Count > 0)
        //{
        //    selectedAddress = addresslist.Single(a => a.UserAddressID == addressid);
        //}
        //if (selectedAddress == null)
        //{
        //    Response.Write(JSONHelper.ObjectToJson(new ReturnValue(ResultType.Fail, "请选择送货地址")));
        //    return;
        //}


        //var sendfee = CalcSendFee(_shoppingCartsList, selectedAddress.AreaID, sendmode);
        //Response.Write("{goodsprice:" + goodprice + ",sendfee:" + sendfee + "}");
        //Response.End();
    }
    private void UserReciveInfo()
    {
    }
    private void PayInfo()
    {
        _payModesList = _payModesManage.QueryALL(true);
        _deliveries = _deliveryManage.Query(true);
    }
    //其实加载的是购物车中的东西，如果OrderID不为空，则加载订单明细
    private void OrderInfo()
    {
        _shoppingCartsList = _shoppingCartsManage.QueryList(_shoppingCartsManage.GetShoppingCartCookieName(this.UserID));
    }
    private void Coupon()
    {
        //AsPage asPage = new AsPage();
        //asPage.CurPage = 0;
        //asPage.PageSize = 10;
        //asPage.TotalCount = 100;
        //_couponList = _couponsManage.QueryListAsPage(_Users.UserID, asPage);
        var couponid = Utility.G<int>("couponid");
        var result = _couponsManage.GetCouponInfoById(couponid, UserID);
        Response.Write(JSONHelper.ObjectToJson(result));
        Response.End();
    }
    private void AddUserAddress()
    {
    }
}